package com.hnx.admin.aurora.utils;

/*
项目名称： admin-aurora
创 建 人: 倔强的头发
创建日期： 2025/6/23   17:13:52 
描   述：
*/
public class ExcelUtils {
    private static final int DEFAULT_COLUMN_WIDTH = 15;
    private static final float DEFAULT_ROW_HEIGHT = 20f;
    private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    /**
     * 导出Excel
     */
    /*
    public static <T> void export(HttpServletResponse response,
                                  List<T> dataList,
                                  Class<T> clazz) throws IOException {
        Workbook workbook = createWorkbook(dataList, clazz);
        String sheetName = resolveSheetName(clazz);
        setResponse(response, sheetName);
        workbook.write(response.getOutputStream());
        workbook.close();
    }*/

    /**
     * 导入Excel
     */
    /*
    public static <T> List<T> importExcel(InputStream inputStream,
                                          Class<T> clazz) throws Exception {
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        validateTemplate(sheet, clazz);
        return parseData(sheet, clazz);
    }
*/
    /**
     * 下载模板
     */
    /*
    public static <T> void downloadTemplate(HttpServletResponse response,
                                            Class<T> clazz) throws IOException {
        Workbook workbook = createTemplateWorkbook(clazz);
        String sheetName = resolveSheetName(clazz);
        setResponse(response, sheetName + "_模板");
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    private static <T> Workbook createWorkbook(List<T> dataList, Class<T> clazz) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(resolveSheetName(clazz));

        List<ExcelField> columns = resolveColumns(clazz);
        createHeader(workbook, sheet, columns);
        fillData(workbook, sheet, dataList, columns);

        return workbook;
    }

    private static <T> List<ExcelColumn> resolveColumns(Class<T> clazz) {
        List<ExcelColumn> columns = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(Excel.class)) {
                Excel excel = field.getAnnotation(Excel.class);
                if (excel.export()) {
                    columns.add(new ExcelColumn(excel, field));
                }
            } else if (field.isAnnotationPresent(Excels.class)) {
                Excels excels = field.getAnnotation(Excels.class);
                for (Excel excel : excels.value()) {
                    if (excel.export()) {
                        columns.add(new ExcelColumn(excel, field));
                    }
                }
            }
        }

        columns.sort(Comparator.comparingInt(c -> c.excel.order()));
        return columns;
    }

    private static void createHeader(Workbook workbook, Sheet sheet, List<ExcelColumn> columns) {
        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(DEFAULT_ROW_HEIGHT);

        CellStyle headerStyle = createHeaderStyle(workbook);

        for (int i = 0; i < columns.size(); i++) {
            ExcelColumn column = columns.get(i);
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(column.excel.name());
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, (column.excel.width() + 1) * 256);
        }
    }

    private static <T> void fillData(Workbook workbook, Sheet sheet,
                                     List<T> dataList,
                                     List<ExcelColumn> columns) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }

        CellStyle dataStyle = createDataStyle(workbook);
        AtomicInteger rowNum = new AtomicInteger(1);

        dataList.forEach(data -> {
            Row row = sheet.createRow(rowNum.getAndIncrement());
            row.setHeightInPoints(DEFAULT_ROW_HEIGHT);

            for (int i = 0; i < columns.size(); i++) {
                ExcelColumn column = columns.get(i);
                Cell cell = row.createCell(i);
                cell.setCellStyle(dataStyle);

                try {
                    Object value = getFieldValue(data, column);
                    setCellValue(cell, value, column.excel);
                } catch (Exception e) {
                    cell.setCellValue(column.excel.defaultValue());
                }
            }
        });
    }

    private static Object getFieldValue(Object obj, ExcelColumn column) throws Exception {
        Field field = column.field;
        field.setAccessible(true);
        Object value = field.get(obj);

        if (value == null) {
            return null;
        }

        // 处理List类型
        if (List.class.isAssignableFrom(field.getType())) {
            return handleListValue((List<?>) value, column.excel);
        }

        // 处理嵌套属性
        if (!StringUtils.isEmpty(column.excel.prefix())) {
            return getNestedValue(value, column.excel.prefix());
        }

        // 处理值转换
        if (!StringUtils.isEmpty(column.excel.readConverterExp())) {
            return convertValue(value.toString(), column.excel.readConverterExp());
        }

        // 处理日期格式化
        if (value instanceof Date) {
            return formatDate((Date) value, column.excel.dateFormat());
        }

        return value;
    }
*/
    /*
    private static String handleListValue(List<?> list, Excel excel) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return "";
        }

        List<String> values = new ArrayList<>();
        for (Object item : list) {
            if (!StringUtils.isEmpty(excel.prefix())) {
                values.add(getNestedValue(item, excel.prefix()).toString());
            } else {
                values.add(item.toString());
            }
        }

        return String.join(",", values);
    }

    private static Object getNestedValue(Object obj, String prefix) throws Exception {
        String[] properties = prefix.split("\\.");
        Object current = obj;

        for (String prop : properties) {
            if (current == null) {
                return null;
            }

            Field field = getField(current.getClass(), prop);
            if (field == null) {
                return null;
            }

            field.setAccessible(true);
            current = field.get(current);
        }

        return current;
    }*/

    // 其他辅助方法...
    /*
    private static Field getField(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            if (clazz.getSuperclass() != null) {
                return getField(clazz.getSuperclass(), fieldName);
            }
            return null;
        }
    }

    private static String convertValue(String value, String converterExp) {
        // 实现值转换逻辑
    }

    private static String formatDate(Date date, String pattern) {
        // 实现日期格式化
    }

    private static <T> String resolveSheetName(Class<T> clazz) {
        // 解析工作表名称
    }

    private static void setResponse(HttpServletResponse response, String sheetName) throws IOException {
        // 设置HTTP响应
    }

    private static CellStyle createHeaderStyle(Workbook workbook) {
        // 创建表头样式
    }

    private static CellStyle createDataStyle(Workbook workbook) {
        // 创建数据样式
    }*/

}
